package com.pactera.madp.cp.service.sync.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.cp.api.bo.SyncOrgInfoBo;
import com.pactera.madp.cp.api.entity.sync.SyncOrgInfoEntity;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.util.sync.SyncUtils;
import com.pactera.madp.cp.common.util.sync.TreeUtil;
import com.pactera.madp.cp.config.SyncConfig;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.mapper.sync.SyncOrgInfoMapper;
import com.pactera.madp.cp.service.sync.SyncOrgInfoHisService;
import com.pactera.madp.cp.service.sync.SyncOrgInfoService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;

@Slf4j
@Service
@AllArgsConstructor
public class SyncOrgInfoServiceImpl extends ServiceImpl<SyncOrgInfoMapper, SyncOrgInfoEntity> implements SyncOrgInfoService {

    private final SyncOrgInfoHisService syncOrgInfoHisService;
    private final SyncConfig syncConfig;

    @Override
    public void addYesterdayToHis() {
        log.debug("机构信息：addYesterdayToHis");
        String date = DateUtil.format(new Date(), Constants.DATE_FORMAT);
        syncOrgInfoHisService.syncOneDay(date);
    }

    @Override
    public void deleteYesterday() {
        log.debug("机构信息：deleteYesterday");
        this.remove(Wrappers.emptyWrapper());
    }

    @Override
    public void parse() {
        log.debug("机构信息：parse");
        DateTime offsetDay = DateUtil.offsetDay(new Date(), -1);
        String fileDate = DateUtil.format(offsetDay, Constants.DATE_FORMAT);
        String filepath = SyncUtils.buildFilePath(syncConfig.getHrPath(), Constants.FN_ORG, fileDate);
        File newestFile = SyncUtils.getNewestFile(filepath);

        List<SyncOrgInfoEntity> entityList
                = SyncUtils.parse(newestFile, Constants.SEPARATOR_STX, SyncOrgInfoEntity.class, syncConfig.getHrCharset());
        log.debug("机构文件解析总数：" + entityList.size());

        entityList = specialHandle(entityList);

        this.saveBatch(entityList);
    }

    @Override
    public void deleteHisOneDay() {
        log.debug("机构信息：deleteHisOneDay");
        DateTime offsetDay = DateUtil.offsetDay(new Date(), -30);
        String date = DateUtil.format(offsetDay, Constants.DATE_FORMAT);
        syncOrgInfoHisService.deleteOneDate(date);
    }

    @Override
    public void syncBusiness() {
        log.debug("机构信息：syncBusiness");
        SyncStateContext.get().setFinalState(true);
    }

    // 机构上移处理
    @SneakyThrows
    private List<SyncOrgInfoEntity> specialHandle(List<SyncOrgInfoEntity> orgList) {
        List<SyncOrgInfoBo> boList = new ArrayList<>();
        SyncOrgInfoBo bo = new SyncOrgInfoBo();
        orgList.forEach(org -> {
            SyncOrgInfoBo b = bo.clone();
            BeanUtil.copyProperties(org, b);
            boList.add(b);
        });

        String idFieldName = "id";
        String parentIdFieldName = "orgGroupCode";
        String childListFieldName = "childList";
        List<SyncOrgInfoBo> trees = TreeUtil.buildTree(boList, idFieldName, parentIdFieldName, childListFieldName);
        SyncOrgInfoBo root = new SyncOrgInfoBo();
        for (SyncOrgInfoBo ob : trees){
            if (StrUtil.equals("-1", ob.getOrgGroupCode())) {
                root = ob;
                break;
            }
        }

        // 获取排除机构id列表
        Set<String> excludeOrg = syncConfig.getExcludeOrg();

        // 过滤掉指定机构
        List<SyncOrgInfoBo> newBoList = new ArrayList<>();
        filterOrg(root, newBoList, excludeOrg);

        List<SyncOrgInfoEntity> newOrgList = new ArrayList<>();
        SyncOrgInfoEntity org = new SyncOrgInfoEntity();
        newBoList.forEach(b -> {
            SyncOrgInfoEntity o = org.clone();
            BeanUtil.copyProperties(b, o);
            newOrgList.add(o);
        });

        //trees = TreeUtil.buildTree(newBoList, idFieldName, parentIdFieldName, childListFieldName);
        return newOrgList;
    }

    // 过滤掉指定的2级、3级机构以及过滤掉全部4，5级机构
    private void filterOrg(SyncOrgInfoBo bo, List<SyncOrgInfoBo> boList, Set<String> excludeIds) {
        if (bo.getTreeId().length() > 9 || excludeIds.contains(bo.getId())) {
            return;
        }
        boList.add(bo);
        List<SyncOrgInfoBo> childList = bo.getChildList();
        if (childList != null) {
            childList.forEach(subOrg -> filterOrg(subOrg, boList, excludeIds));
            bo.setChildList(null);
        }
    }

}